/*
* @Author: Choisaaaa
* @Date: 2018/5/6  16:01
* 后台登录组件
*/

import React from "react";

import './login.scss';
import Mutil from "util/mm.jsx";
import User         from 'service/admin-service.jsx'
const _mm = new Mutil();
const _user = new User();

class Login extends  React.Component{
    constructor(props){
        super(props);
        this.state = {
            username : "",//用户名
            password : "",//密码
            redirect: _mm.getUrlParam('redirect') || '/'
        }
    }
    componentWillMount(){
        document.title = '登录 - ADMIN';
    }
    onInputChange(e){//当输入状态发生改变
        let inputValue = e.target.value,
            inputName = e.target.name;
        this.setState({
            [inputName] : inputValue //当变量名是一个变量时用[]
        });
    }
    onInputKeyUp (e){
        if(e.keyCode === 13){
            this.onSubmit();
        }
    }
    onSubmit(e){//点击提交
        let loginInfo = {
            adminName : this.state.username,
            password : this.state.password
        };
        let checkResult = _user.checkLoginInfo(loginInfo);
        if(checkResult.status){//验证通过
            _user.login(loginInfo).then((res)=>{
                _mm.setStorage("loginAdminInfo", res);//将验证通过的管理员信息保存到本地存储
                this.props.history.push(this.state.redirect);
            },(err)=>{
                _mm.errorTips(err.msg);
            });
        }
    }
    render(){
        return(
            <div className="col-md-4 col-md-offset-4">
                <div className="panel panel-default login-panel">
                    <div className="panel-heading">Login</div>
                    <div className="panel-body">
                        <div>
                            <div className="form-group">
                                <input type="text"
                                       name="username"
                                       className="form-control"
                                       placeholder="请输入用户名"
                                       onKeyUp={e => this.onInputKeyUp(e)}
                                       onChange={e => this.onInputChange(e)}/>
                            </div>
                            <div className="form-group">
                                <input type="password"
                                       name="password"
                                       className="form-control"
                                       placeholder="请输入密码"
                                       onKeyUp={e => this.onInputKeyUp(e)}
                                       onChange={e => this.onInputChange(e)}/>
                            </div>
                            <button className="btn btn-lg btn-primary btn-block"
                                    onClick={e => {this.onSubmit(e)}}>登录</button>
                        </div>
                    </div>
                </div>
            </div>
        )
    }

}

export default Login;